package elven.d.web.future.hello;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

import org.apache.commons.lang.math.RandomUtils;

import com.alibaba.fastjson.JSONObject;

import elven.d.common.log.LogFactory;

public class TvFutureTask {
	
	private static final ExecutorService executorService = Executors.newFixedThreadPool(30);
	
	public String tvJSONDetail(String param) throws InterruptedException, ExecutionException{
		if(!param.startsWith("letv")){
			return null;
		}
		FutureTask<String> futureTask = new FutureTask<String>(new Callable<String>() {
			@Override
			public String call() throws Exception {
				return new TvFutureTask().letv(RandomUtils.nextBoolean()?"osc-1":"pwd-1");
			}
		});
		/*Future<String> future = executorService.submit(new Callable<String>() {
			@Override
			public String call() throws Exception {
				return new TvFutureTask().letv(RandomUtils.nextBoolean()?"osc-1":"pwd-1");
			}
		});*/
		JSONObject detail = new JSONObject();
		detail.put("money", getLetvMoneybyDb(RandomUtils.nextBoolean()?"osc-1":"pwd-1"));
		//detail.put("tv", future.get());
		detail.put("tv", futureTask.get());
		detail.put("param", param);
		return detail.toJSONString();
	}

	public int getLetvMoneybyDb(String productType){
		return productType.equals("osc-1")?800:850;
	}
	
	/**
	 * 从乐视那边获取对应的型号详细数据
	 * @param productType 型号
	 * @return null | 型号数据
	 */
	public String letv(String productType){
		JSONObject letvParams = new JSONObject();
		if(productType.equals("osc-1")){
			letvParams.put("company", "z1");
			letvParams.put("size", 21);
		}else{
			letvParams.put("company", "东丽");
			letvParams.put("size", 23);
		}
		LogFactory.d().info(productType);
		return letvParams.toJSONString();
	}
	
	public void close(){
		executorService.shutdown();
	}
	
	public static void main(String[] args) {
		try {
			long currentMillis = System.currentTimeMillis();
			LogFactory.d().info("Current Time {}", currentMillis);
			TvFutureTask futureTask = new TvFutureTask();
			for(int i = 0; i < 10000; i++){
				LogFactory.d().info(futureTask.tvJSONDetail("letv"+i));;
			}
			long endFuture = System.currentTimeMillis();
			LogFactory.d().info("futureTaskEnd Time {}, time : {}", endFuture, endFuture - currentMillis);
			//futureTask.close();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		
	}
	
}
